//
//  ViewController.swift
//  第二天项目演练
//
//  Created by mac on 16/5/9.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

class ViewController: UITableViewController {

    var personArray :[Person]?
    override func viewDidLoad() {
        super.viewDidLoad()
        let closure = { (result :[Person]) in
        
            self.personArray = result
            self.tableView.reloadData()
        }
        
        loadData(closure)
    }
    
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        guard let destinationVC = segue.destinationViewController as? DetailViewController else {
        
            return
        }
        
        guard let indexPath = tableView.indexPathForSelectedRow else {
        
            return
        }
        
        destinationVC.person = personArray![indexPath.row]
        destinationVC.closure = {
        
            self.tableView.reloadData()
        }
    }


}

extension ViewController {
    func loadData(callBack :(result :[Person]) -> ()) {
        dispatch_async(dispatch_get_global_queue(0, 0)) { () -> Void in
            
//            var nmArray :[Person]?
            var nmArray = [Person]()
            for i in 0..<30 {
                let name :String = "林青霞\(i)"
                let age :Int = 15 + random() % 16
                let person = Person(dict: ["name" : name,"age" : age])
                nmArray.append(person)
            }
            dispatch_async(dispatch_get_main_queue()) { () -> Void in
                callBack(result: nmArray)
            }
        }
    }
}


extension ViewController {

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return personArray?.count ?? 0
    }
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("person", forIndexPath: indexPath) as! PersonTableViewCell
        
        cell.person = personArray![indexPath.row]
        
        return cell
    }
}
